﻿#region namespaces

using System;
using System.Configuration;
using System.IO;
using System.Web.UI.WebControls;

using Artem.Web.UI.Controls;

using NotesFor;

using SLIITPro.Controls;
using SLIITPro.Data.Extension;
using SLIITPro.Data.Entity;
using SLIITPro.Core;

using Facebook;    // This is reference from a dll see the References for the dll
using Facebook.Rest;
using Facebook.Session;
using Facebook.Utility;
using Facebook.Schema;
using System.Collections.Generic;

#endregion

namespace SLIITPro
{
    public partial class Place : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            /* connectSession = new ConnectSession(APPLICATION_KEY, SECRET_KEY);
             facebookAPI = new Api(connectSession);
             user = facebookAPI.Users.GetInfo();*/

            _facebookAPI = (Api)Session["facebookApi"];


            btnSubmitComment.Click += new EventHandler(btnSubmitComment_Click);
            if ((Session["country"] == null || Session["city"] == null) || Session["street"] == null)
                Response.Redirect(CoreSettings.RelativeWebRoot, true);
            else
            {
                if (!string.IsNullOrEmpty(Request.QueryString["id"]))
                    if (Session["id"] == null || Session["id"].ToString() != Request.QueryString["id"])
                    {
                        Session["id"] = Request.QueryString["id"];
                    }

                if (Session["id"] == null || !Utility.IsNumberId(Session["id"].ToString())) return;
                GetBusinessItem(int.Parse(Session["id"].ToString()));
                GetCommentsByBusinessId(int.Parse(Session["id"].ToString()));
                if (Request.QueryString["deletecomment"] != null) DeleteComment(int.Parse(Session["id"].ToString()));
            }
        }


        private Gallery _imageGallery;
        private BusinessItem _item;
        private BusinessItemExtension _itemExtension;
        private void GetBusinessItem(int itemId)
        {
            if (string.IsNullOrEmpty(itemId.ToString())) return;
            try
            {
                _itemExtension = new BusinessItemExtension();

                var table = _itemExtension.SelectBusiness(itemId);
                _item = new BusinessItem(table.Rows[0]);
                lblBusinessName.Text = _item.BName;
                lblCity.Text = _item.BCity;
                lblStreet.Text = _item.BStreet;
                lblPhone.Text = _item.BPhone;
                lblEmail.Text = _item.BEmail;
                SetWidgetContent();
                SetGoogleMap();
                if (!string.IsNullOrEmpty(_item.BImageFolderID))
                {
                    var path = CoreSettings.GlobalBusinessImageRoot + _item.BImageFolderID + "/";
                    if (Directory.Exists(Server.MapPath(path)))
                    {
                        _imageGallery = new Gallery
                                    {
                                        FolderUrl = CoreSettings.GlobalBusinessImageRoot + _item.BImageFolderID,
                                        Size = 100,
                                        AlbumTitle = _item.BName
                                    };
                        ImageGallery.Controls.Add(_imageGallery);
                    }
                }
            }
            catch (Exception ex) { throw ex; }
        }

        private void SetGoogleMap()
        {
            string address = string.Concat(_item.BCity, ",", Utility.GetCountry(_item.BCountry));
            GoogleMapBusiness.Address = address;
            GoogleMapBusiness.Markers.Clear();
            GoogleMapBusiness.Markers.Add(new GoogleMarker(address));
        }

        private SLIITPro.Data.Entity.Users _users;
        private void SetWidgetContent()
        {
            WidgetComment.RatingText = string.Format("Currently rated {0:f2} by {1} people", _item.BRating, _item.BRater);
            WidgetComment.RatingValue = (int)_item.BRating;
            WidgetComment.BusinessId = int.Parse(Session["id"].ToString());
            if (Page.User.Identity.IsAuthenticated && !Page.User.IsInRole("information"))
            {
                _users = new SLIITPro.Data.Entity.Users(new UserExtension().SelectUser("Email", Page.User.Identity.Name).Rows[0]);
                WidgetComment.UserId = _users.UserId;
            }
        }

        private CommentExtension _commentExtension;
        private Data.Entity.Comments _comments;
        void btnSubmitComment_Click(object sender, EventArgs e)
        {
            if (Session["id"] == null) return;
            _commentExtension = new CommentExtension();
            _comments = new SLIITPro.Data.Entity.Comments
                            {
                                Id = Guid.NewGuid().ToString(),
                                Author = Page.User.Identity.IsAuthenticated ? GetRoles() : "anonymous",
                                BId = int.Parse(Session["id"].ToString()),
                                DateCreated = DateTime.Now,
                                Content = txtComment.Text.Trim(),
                                Email = Page.User.Identity.IsAuthenticated ? User.Identity.Name : txtEmail.Text.Trim(),
                                IsApproved = User.IsInRole("administrator") || User.IsInRole("business") ? true : false
                            };
            _commentExtension.AddComment(_comments);
            Utility.ClearContent(this.tblComment);
            lblAwaiting.Text = User.IsInRole("administrator") || User.IsInRole("business") ? "thank you for your Comment" : "thank you for your Comment and it's awaiting for a moderation";
            GetCommentsByBusinessId(int.Parse(Session["id"].ToString()));
            upcomment.Update();
        }


        private void GetCommentsByBusinessId(int id)
        {
            if (string.IsNullOrEmpty(id.ToString())) return;
            var path = CoreSettings.TemplateRoot + "comment.ascx";
            _commentExtension = new CommentExtension();
            var listCmt = _commentExtension.SelectComment("cmBId", id.ToString());
            cmtPlace.Controls.Clear();
            foreach (var commentz in listCmt)
            {
                if (commentz.IsApproved)
                {
                    var control = (Comment)LoadControl(path);
                    control.Comments = commentz;
                    cmtPlace.Controls.Add(control);
                }
            }
        }

        private void DeleteComment(int id)
        {
            _commentExtension = new CommentExtension();
            var listcmt = _commentExtension.SelectComment("cmBId", id.ToString());
            foreach (var comment in listcmt)
            {
                if (comment.Id == Request.QueryString["deletecomment"])
                {
                    _commentExtension.DeleteCommentByCommentId(Request.QueryString["deletecomment"]);
                }
            }
            var url = string.Format("{0}?id={1}", Request.Path, Session["id"]);
            Response.Redirect(url);
        }

        private string GetRoles()
        {
            return Page.User.IsInRole("administrator") ? "Administrator" : (Page.User.IsInRole("information")
                                                                                ? "Information User"
                                                                                : (Page.User.IsInRole("business")
                                                                                       ? "Business User" : string.Empty));
        }

        protected void btnGetroot_Click(object sender, EventArgs e)
        {
            _itemExtension = new BusinessItemExtension();
            _item = new BusinessItem(_itemExtension.SelectBusiness(int.Parse(Session["id"].ToString())).Rows[0]);
            var itemAddress = string.Format("{0},{1}", _item.BCity, Utility.GetCountry(_item.BCountry));
            var userAddress = string.Format("{0},{1},{2}", Session["street"], Session["city"], Utility.GetCountry(Session["country"].ToString()));
            var query = string.Format("from: {0} to: {1}", itemAddress, userAddress);
            GoogleMapBusiness.Markers.Clear();
            GoogleMapBusiness.Directions.Clear();
            GoogleMapBusiness.Directions.Add(new GoogleDirection(query));
            upGoogleMap.Update();

        }

        private Api _facebookAPI;
        private ConnectSession _connectSession;
        private Facebook.Schema.user user;
        protected void btnPublish_Click(object sender, EventArgs e)
        {

            if (FbConnectionManager.isConnected())
            {
                try
                {
                    PublishToFacebook();
                }
                catch
                {
                    lblAwaiting.Text = "Error occured";
                }
            }
            else
            {
                _connectSession = new ConnectSession(ConfigurationManager.AppSettings["FBApiKey"],
                                               ConfigurationManager.AppSettings["FBSecret"]);
                _facebookAPI = new Api(_connectSession);
            }


        }

        private void PublishToFacebook()
        {
            _itemExtension = new BusinessItemExtension();
            _item = new BusinessItem(_itemExtension.SelectBusiness(int.Parse(Session["id"].ToString())).Rows[0]);

            attachment attach = new attachment { caption = "I found this great place from LBIS, Check it out..!!", description = String.Format("This, {0} is great place and its located at {1}", _item.BName, _item.BCity), href = string.Format("{0}PlaceInfo.aspx?id={1}", CoreSettings.AbsoluteUrl, _item.BId), name = _item.BName };
            attachment_media attach_media = new attachment_media { type = attachment_media_type.image };
            attachment_media_image image = new attachment_media_image { type = attachment_media_type.image, href = "http://www.ischool.berkeley.edu/newsandevents/news/20100224privacyreport/", src = "http://www.ischool.berkeley.edu/files/imagecache/sidebar-inner/images/geolocation_0.png" };

            // Media has to be passed as a list
            List<attachment_media> attach_media_list = new List<attachment_media>();
            attach_media_list.Add(image);
            attach.media = attach_media_list;

            // This is the action link and this is what happend when the viewer clicks on the attachement

            List<action_link> actionlink = new List<action_link>();
            action_link al1 = new action_link();
            al1.href = string.Format("{0}PlaceInfo.aspx?id={1}", CoreSettings.AbsoluteUrl, _item.BId);
            al1.text = String.Format("{0},{1}", _item.BName, _item.BCity);
            actionlink.Add(al1);


            _facebookAPI.Permissions.BeginPermissionsMode(ConfigurationManager.AppSettings["FBApiKey"]);
            _facebookAPI.ExtendedPermissionUrl(Enums.ExtendedPermissions.publish_stream);

            //string.Format("http://facebook.com/authorize.php?api_key={0}&v=1.0&ext_perm=publish_stream",);
            _facebookAPI.Stream.Publish("I found this great place", attach, actionlink, null, 0);
        }

    }
}